import type { ForwardedRef } from 'react';
import { forwardRef, useImperativeHandle, useState } from 'react';
import { ModalForm } from '@ant-design/pro-form';

export interface BasicModalFormRef {
  open: () => void;
  close: () => void;
}

function BasicModalForm(
  props: {
    title?: React.ReactNode;
    onSubmit?: (data: AnyFields) => Promise<boolean> | undefined;
    onReload?: () => void;
    values?: AnyFields;
    AfterClose?: () => void;
    children?: React.ReactNode;
  },
  ref: ForwardedRef<BasicModalFormRef>,
) {
  const { title, onSubmit, onReload, values = {}, AfterClose, children } = props;

  const [visible, setVisible] = useState<boolean>(false);

  useImperativeHandle(ref, () => ({
    open: () => setVisible(true),
    close: () => setVisible(false),
  }));

  return (
    <ModalForm
      title={title}
      visible={visible}
      initialValues={values}
      modalProps={{
        destroyOnClose: true,
      }}
      onVisibleChange={(v) => {
        if (visible !== v) {
          setVisible(v);
        }
        if (!v && AfterClose) {
          AfterClose();
        }
      }}
      onFinish={async (value) => {
        if (onSubmit) {
          const success = await onSubmit(value);

          if (success) {
            setVisible(false);

            if (onReload) {
              onReload();
            }
          }
        } else {
          setVisible(false);
        }
      }}
    >
      {children}
    </ModalForm>
  );
}

export default forwardRef(BasicModalForm);
